/*
 * Copyright 2010 David de Mingo
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.shalma.internal.persistence;

import java.lang.reflect.Constructor;

import org.shalma.model.Id;
import org.shalma.model.Property;
import org.shalma.persistence.PersistenceException;
import org.shalma.persistence.Translator;

public class PropertyTranslator<T> implements Translator<Property<T>, T> {

	private String typeId;

	@SuppressWarnings("rawtypes")
	private Constructor constructor;

	public <P extends Property<T>> PropertyTranslator(Class<P> type) {

		Id annotation = type.getAnnotation(Id.class);
		if (annotation == null)
			throw new PersistenceException(type, "@Id not found.");

		typeId = annotation.value();

		try {

			Class<?> returnType = type.getDeclaredMethod("asProperty")
					.getReturnType();
			constructor = type.getDeclaredConstructor(returnType);

		} catch (Exception e) {
			throw new PersistenceException(e);
		}

		constructor.setAccessible(true);
	}

	@Override
	public String getTypeId() {
		return typeId;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Property<T> toType(T property) {

		try {

			return (Property<T>) constructor.newInstance(property);

		} catch (Exception e) {
			throw new PersistenceException(e);
		}
	}

	@Override
	public T toProperty(Property<T> type) {
		return type.asProperty();
	}
}
